# (C) 2007 Jorik Blaas, use in any way as you please.

def convertTop2Svg(file_name):
    out = ""
    f = file(file_name,"rb")
    f.read(32) # skip header
    out += """<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
"""
    out += '<path d="'
    drawing = False
    bytes = 0
    while True:
        packet = f.read(6)
        if len(packet) < 6:
            break
        xcoord = ord(packet[4])*256+ord(packet[3])
        ycoord = ord(packet[2])*256+ord(packet[1])

        if packet[0]==chr(0):
            # pen up
            drawing = False
            code = "L"
        else:
            # pen down
            if drawing:
                code = "L"
            else:
                out += '" style="fill:none;stroke:black;stroke-width:1" />'
                out += '<path d="'
                code = "M"
                drawing = True
    
        ycoord = 12000-ycoord
        out += " %s %.2f %.2f"%(code,xcoord/10.0,ycoord/10.0) #, (ord(packet[5])+128)%256-128
    
    out += '" style="fill:none;stroke:black;stroke-width:1" />'
    out += "</svg>"
    f.close()
    return out

import sys
import getopt
import os
import re

options = getopt.getopt(sys.argv[1:], "ch", ["top=", "svg=", "top-dir=", "svg-dir=", "help", "clean"])
help = [x[1] for x in filter(lambda x:x[0]=='-h' or x[0]=='--help', options[0])]
clean = [x[1] for x in filter(lambda x:x[0]=='-c' or x[0]=='--clean', options[0])]
tops = [x[1] for x in filter(lambda x:x[0]=='--top', options[0])]
svgs = [x[1] for x in filter(lambda x:x[0]=='--svg', options[0])]
top_dirs = [x[1] for x in filter(lambda x:x[0]=='--top-dir', options[0])]
svg_dirs = [x[1] for x in filter(lambda x:x[0]=='--svg-dir', options[0])]

if help:
    print "Usage top2svg.py [OPTION]..."
    print " --top=FILE            Top input file"
    print " --svg=FILE            Svg output file"
    print " --top-dir=PATH        Import all TOP files in the PATH"
    print " --svg-dir=PATH        Export svg into PATH"
    print " -c --clean            Remove any imported TOP file"
    print " -h --help             This usage screen"
    exit(0)

for top_path in top_dirs:
   files = os.listdir(top_path)
   match = "(.*?\.TOP)"
   tops += [top_path + "/" + re.findall(match, file_name)[0] for file_name in files if re.findall(match, file_name)]

topNames2svgNames = {}

if (len(tops) == len(svgs)):
    for i in range(len(tops)):
        topNames2svgNames[tops[i]] = svgs[i]
elif (len(svg_dirs) == 1):
    svg_dir = svg_dirs[0]
    for top in tops:
        match = ".*/(.*?)\.TOP"
        topNames2svgNames[top] = svg_dir + "/" + re.findall(match, top)[0] + ".svg"

i=0
total=float(len(topNames2svgNames.items()))
for top_svg in topNames2svgNames.items():
    svg_f = open(top_svg[1], "w")
    svg_f.write(convertTop2Svg(top_svg[0]))
    svg_f.close()
    if clean:
        os.unlink(top_svg[0])
    i+=1
    print "[%d/%d Converted]: %s" % (i, total, top_svg[0])
